package net.wanho.shop.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * IoC容器工具类，用于获取IoC容器中的bean
 */
@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    /**
     * 静态属性，保存ApplicationContext对象，即IoC容器
     */
    private static ApplicationContext ac;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ac = applicationContext;
    }

    /**
     * 根据名称获取bean
     *
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return ac.getBean(beanName);
    }

    /**
     * 根据类型获取bean
     *
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> tClass) {
        return ac.getBean(tClass);
    }
}
